// Three.js 场景设置
let scene, camera, renderer, controls;
let model, mixer;
let autoRotate = true;

function initThreeJS() {
    const container = document.getElementById('canvas-container');
    const canvas = document.getElementById('three-canvas');
    
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x1a1a1a);
    
    // 创建相机
    const aspect = container.clientWidth / container.clientHeight;
    camera = new THREE.PerspectiveCamera(45, aspect, 0.1, 1000);
    camera.position.set(0, 2, 5);
    
    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ 
        canvas: canvas,
        antialias: true,
        alpha: true 
    });
    renderer.setSize(container.clientWidth, container.clientHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    
    // 添加灯光
    setupLights();
    
    // 添加控制器
    setupControls();
    
    // 添加默认模型（弥勒佛像占位符）
    addDefaultModel();
    
    // 窗口大小调整
    window.addEventListener('resize', onWindowResize);
}

function setupLights() {
    // 环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);
    
    // 主光源
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(5, 10, 5);
    directionalLight.castShadow = true;
    directionalLight.shadow.camera.near = 0.1;
    directionalLight.shadow.camera.far = 50;
    directionalLight.shadow.camera.left = -10;
    directionalLight.shadow.camera.right = 10;
    directionalLight.shadow.camera.top = 10;
    directionalLight.shadow.camera.bottom = -10;
    scene.add(directionalLight);
    
    // 补光
    const fillLight = new THREE.DirectionalLight(0xffffff, 0.3);
    fillLight.position.set(-5, 5, -5);
    scene.add(fillLight);
}

function setupControls() {
    // 创建轨道控制器
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.screenSpacePanning = false;
    controls.minDistance = 1;
    controls.maxDistance = 10;
    controls.maxPolarAngle = Math.PI / 2;
    
    // 添加触摸支持
    controls.touches = {
        ONE: THREE.TOUCH.ROTATE,
        TWO: THREE.TOUCH.DOLLY_PAN
    };
}

function addDefaultModel() {
    // 创建弥勒佛像占位符（金色球体）
    const geometry = new THREE.SphereGeometry(1, 32, 32);
    const material = new THREE.MeshPhongMaterial({
        color: 0xffd700,
        shininess: 100,
        specular: 0x222222
    });
    
    const placeholder = new THREE.Mesh(geometry, material);
    placeholder.castShadow = true;
    placeholder.receiveShadow = true;
    scene.add(placeholder);
    
    // 添加底座
    const baseGeometry = new THREE.CylinderGeometry(1.5, 1.5, 0.2, 32);
    const baseMaterial = new THREE.MeshPhongMaterial({
        color: 0x8b4513,
        shininess: 30
    });
    const base = new THREE.Mesh(baseGeometry, baseMaterial);
    base.position.y = -1.1;
    base.receiveShadow = true;
    scene.add(base);
}

function onWindowResize() {
    const container = document.getElementById('canvas-container');
    camera.aspect = container.clientWidth / container.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(container.clientWidth, container.clientHeight);
}

function animate() {
    requestAnimationFrame(animate);
    
    if (autoRotate && model) {
        model.rotation.y += 0.005;
    }
    
    controls.update();
    renderer.render(scene, camera);
}

// 添加OrbitControls（简化版本）
THREE.OrbitControls = function(object, domElement) {
    this.object = object;
    this.domElement = domElement;
    
    this.enableDamping = false;
    this.dampingFactor = 0.05;
    this.enableZoom = true;
    this.enableRotate = true;
    this.enablePan = true;
    this.minDistance = 0;
    this.maxDistance = Infinity;
    this.minPolarAngle = 0;
    this.maxPolarAngle = Math.PI;
    
    const scope = this;
    const rotateSpeed = 1.0;
    const zoomSpeed = 0.95;
    const panSpeed = 1.0;
    
    let rotateStart = new THREE.Vector2();
    let rotateEnd = new THREE.Vector2();
    let rotateDelta = new THREE.Vector2();
    
    let panStart = new THREE.Vector2();
    let panEnd = new THREE.Vector2();
    let panDelta = new THREE.Vector2();
    
    let spherical = new THREE.Spherical();
    let sphericalDelta = new THREE.Spherical();
    
    let scale = 1;
    let panOffset = new THREE.Vector3();
    
    let mouseButtons = {
        LEFT: THREE.MOUSE.ROTATE,
        MIDDLE: THREE.MOUSE.DOLLY,
        RIGHT: THREE.MOUSE.PAN
    };
    
    this.update = function() {
        const offset = new THREE.Vector3();
        const quat = new THREE.Quaternion().setFromUnitVectors(object.up, new THREE.Vector3(0, 1, 0));
        const quatInverse = quat.clone().invert();
        
        const lastPosition = new THREE.Vector3();
        const lastQuaternion = new THREE.Quaternion();
        
        return function update() {
            const position = scope.object.position;
            offset.copy(position).sub(scope.target);
            offset.applyQuaternion(quat);
            
            spherical.setFromVector3(offset);
            
            if (scope.enableDamping) {
                spherical.theta += sphericalDelta.theta * scope.dampingFactor;
                spherical.phi += sphericalDelta.phi * scope.dampingFactor;
            } else {
                spherical.theta += sphericalDelta.theta;
                spherical.phi += sphericalDelta.phi;
            }
            
            spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
            spherical.makeSafe();
            spherical.radius *= scale;
            spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius));
            
            scope.target.add(panOffset);
            offset.setFromSpherical(spherical);
            offset.applyQuaternion(quatInverse);
            position.copy(scope.target).add(offset);
            scope.object.lookAt(scope.target);
            
            if (scope.enableDamping) {
                sphericalDelta.theta *= (1 - scope.dampingFactor);
                sphericalDelta.phi *= (1 - scope.dampingFactor);
                panOffset.multiplyScalar(1 - scope.dampingFactor);
            } else {
                sphericalDelta.set(0, 0, 0);
                panOffset.set(0, 0, 0);
            }
            
            scale = 1;
            
            if (lastPosition.distanceToSquared(scope.object.position) > 0.0001 ||
                8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > 0.0001) {
                lastPosition.copy(scope.object.position);
                lastQuaternion.copy(scope.object.quaternion);
            }
        };
    }();
    
    this.target = new THREE.Vector3();
    
    const onMouseDown = function(event) {
        event.preventDefault();
        
        switch (event.button) {
            case 0:
                rotateStart.set(event.clientX, event.clientY);
                break;
            case 2:
                panStart.set(event.clientX, event.clientY);
                break;
        }
        
        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    };
    
    const onMouseMove = function(event) {
        event.preventDefault();
        
        switch (event.button) {
            case 0:
                rotateEnd.set(event.clientX, event.clientY);
                rotateDelta.subVectors(rotateEnd, rotateStart);
                
                sphericalDelta.theta -= 2 * Math.PI * rotateDelta.x / domElement.clientHeight * rotateSpeed;
                sphericalDelta.phi -= 2 * Math.PI * rotateDelta.y / domElement.clientHeight * rotateSpeed;
                
                rotateStart.copy(rotateEnd);
                break;
            case 2:
                panEnd.set(event.clientX, event.clientY);
                panDelta.subVectors(panEnd, panStart);
                
                panOffset.x += panDelta.x * panSpeed;
                panOffset.y -= panDelta.y * panSpeed;
                
                panStart.copy(panEnd);
                break;
        }
    };
    
    const onMouseUp = function() {
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    };
    
    const onWheel = function(event) {
        event.preventDefault();
        
        if (event.deltaY < 0) {
            scale /= zoomSpeed;
        } else {
            scale *= zoomSpeed;
        }
    };
    
    domElement.addEventListener('mousedown', onMouseDown);
    domElement.addEventListener('wheel', onWheel);
    domElement.addEventListener('contextmenu', function(event) { event.preventDefault(); });
    
    // 触摸支持
    let touchStartX = 0;
    let touchStartY = 0;
    
    domElement.addEventListener('touchstart', function(event) {
        if (event.touches.length === 1) {
            touchStartX = event.touches[0].clientX;
            touchStartY = event.touches[0].clientY;
            rotateStart.set(touchStartX, touchStartY);
        }
    });
    
    domElement.addEventListener('touchmove', function(event) {
        event.preventDefault();
        
        if (event.touches.length === 1) {
            const touchX = event.touches[0].clientX;
            const touchY = event.touches[0].clientY;
            
            rotateEnd.set(touchX, touchY);
            rotateDelta.subVectors(rotateEnd, rotateStart);
            
            sphericalDelta.theta -= 2 * Math.PI * rotateDelta.x / domElement.clientHeight * rotateSpeed;
            sphericalDelta.phi -= 2 * Math.PI * rotateDelta.y / domElement.clientHeight * rotateSpeed;
            
            rotateStart.copy(rotateEnd);
        }
    });
};

THREE.MOUSE = {
    LEFT: 0,
    MIDDLE: 1,
    RIGHT: 2,
    ROTATE: 0,
    DOLLY: 1,
    PAN: 2
};
